import { useState, useEffect } from 'react';
import { FormPanelObject } from 'lfun-bg-comp';

type FetchDataFunction = (params: any) => Promise<{ data: any; total?: number }>;
type FilterFunction = (data: any[]) => any[];
type FilterParamsFunction = (params: any) => any;

interface FetchDataOptions {
  filterFunction?: FilterFunction;
  filterParamsFun?: FilterParamsFunction;
}

function useFetchData(fetchData: FetchDataFunction, options: FetchDataOptions = {}) {
  const { filterFunction, filterParamsFun } = options;
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState<{ current: number; pageSize: number; total: number }>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [form, setForm] = useState<FormPanelObject>();

  const loadData = async (params = {}) => {
    setLoading(true);
    try {
      const req = {
        ...pagination,
        ...form?.getFieldsValue(),
        ...params,
      };
      const filteredReq = Object.fromEntries(
        Object.entries(req).filter(([_, value]) => value !== '' && value !== undefined)
      );

      const finalParams = filterParamsFun ? filterParamsFun(filteredReq) : filteredReq;
      const response = await fetchData(finalParams);
      const processedData = filterFunction ? filterFunction(response.data) : response.data;

      setData(processedData);
      setPagination(prevPagination => ({
        ...prevPagination,
        total: response.total ?? prevPagination.total,
      }));
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, [pagination.current, pagination.pageSize]);

  return {
    data,
    loading,
    pagination,
    form,
    setPagination,
    setForm,
    loadData,
  };
}

export default useFetchData;
